package cn.xy.commons.util;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.xy.commons.bean.Area;
import lombok.extern.slf4j.Slf4j;
import org.lionsoul.ip2region.xdb.Searcher;

import java.util.List;
import java.util.stream.Collectors;

/**
 * ip解析工具类
 *
 *  @author xy
 */
@Slf4j
public class IpUtil {

    /**
     * IP 查询器
     */
    private static Searcher ipSearcher;

    private IpUtil() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 根据IP地址获取地址
     * 查询国外ip时，只返回国家
     *
     * @param ip ip
     * @return 解析的地址
     */
    public static Area getAddress(String ip) {
        if (CharSequenceUtil.isEmpty(ip)) {
            return null;
        }
        try {
            if (ipSearcher == null) {
                byte[] bytes = ResourceUtil.readBytes("ip2region.xdb");
                ipSearcher = Searcher.newWithBuffer(bytes);
            }
            String address = ipSearcher.search(ip);
            if (CharSequenceUtil.isEmpty(address)) {
                return null;
            }
            return IpUtil.strToArea(address);
        } catch (Exception e) {
            log.error("IpUtil failed : {}", e.getMessage());
        }
        return null;
    }

    private static Area strToArea(String address) {
        int length = 5;
        if (CharSequenceUtil.isEmpty(address)) {
            return null;
        }
        List<String> infoList = CharSequenceUtil.split(address, "|");
        if (infoList.size() != length) {
            return null;
        }
        infoList = infoList.stream().map(i -> "0".equals(i) ? null : i).collect(Collectors.toList());
        Area area = new Area();
        area.setCountry(infoList.get(0));
        area.setRegion(infoList.get(1));
        area.setProvince(infoList.get(2));
        area.setCity(infoList.get(3));
        area.setIsp(infoList.get(4));
        return area;
    }

}
